#!/usr/bin/env gosh
(use srfi-1)
(use sxml.ssax)
(use sxml.serializer)
(use sxml.tools)
(use sxml.sxpath)
(use sxml.tree-trans)
(use gauche.sequence)
(use gauche.process)
(use gauche.parseopt)

(define (main args)
  (let-args (cdr args)
      ((option-n "n|node=s" "")
       (cmd    "c|cmd=s" #f)
       (debug  "p" #f)
       . file)
    (define sxml (if (null? file)
		   (ssax:xml->sxml (current-input-port) '())
		   (call-with-input-file (car file) (lambda (in)
						      (ssax:xml->sxml in '())))))
    (let ((nodes ((sxpath option-n) sxml))
	  (keys ((sxpath (string-append option-n "/text()")) sxml)))
    (cond
     (debug
      (for-each print keys))
     (else
      (tr! sxml cmd nodes keys)
      (print (srl:sxml->html sxml))))))
  (exit 0))

(define (run-cmd cmd keys)
 (call-with-process-io
  cmd
  (lambda (in out)
    (for-each (lambda (x)
		(format out "~a\n" x))
	      keys)
    (flush out)
    (close-output-port out)
    (port->string-list in))
  :on-abnormal-exit :ignore))

(define (tr! sxml cmd nodes keys)
  (for-each (lambda (node key)
	      (sxml:change-content! node (list key)))
	    nodes
	    (if cmd 
	      (run-cmd cmd keys)
	      keys)))
